<script setup lang="ts">
/**
 * @see {@link https://vuejs.org/api/sfc-script-setup.html#defineoptions}
 */
import {
  getUserPage,
  postRoleAll,
  postAdminAdd,
  postAdminInfo,
  postAdminDel,
  updateLoginPwd
} from "@/api/user";
import { UserQuery, UserPageVO, PageQuery } from "@/api/user/types";

const loading = ref(false);
const total = ref(0);
const dialog = reactive<DialogOption>({
  visible: false,
});

const queryParams = reactive<UserQuery>({
  page: 1,
  ps: 10,
});

const formData = reactive<any>({
  account: '',
  nickname: '',
  login_pwd: "",
  login_pwd_confirmation: "",
  is_root: 2,
  role_ids: []
});

const rules = reactive({
  account: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
  nickname: [{ required: true, message: "请输入角色编码", trigger: "blur" }],
  login_pwd: [{ required: true, message: "请选择数据权限", trigger: "blur" }],
  login_pwd_confirmation: [{ required: true, message: "请选择状态", trigger: "blur" }],
});


const userList = ref<UserPageVO[]>();

const roleFormRef = ref(ElForm);

/**
 * 查询
 */
function handleQuery() {
  loading.value = true;
  getUserPage(queryParams)
    .then(({ data }) => {
      userList.value = data.data;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置查询 */
function resetQuery() {
  handleQuery();
}

const roleList = ref<any>([]);

let adminId = ref<number | string>();

// 打开新增修改弹窗
const openDialog = (data?: any) => {
  postRoleAll().then((res: any) => {
    roleList.value = res.data.lists;
  })

  dialog.visible = true;
  if (data) {
    adminId.value = data.id;
    Object.assign(formData, data);
    dialog.title = "修改管理员";
  } else {
    adminId.value = '';
    dialog.title = "新增管理员";
  }
}

// 删除管理员
const handleDelete = (id: number) => {
  ElMessageBox.confirm("确认删除该条的数吗?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    postAdminDel({ ids: [id] }).then(() => {
      ElMessage.success("删除成功");
      handleQuery();
    });
  }).catch(() => ElMessage.info("已取消删除"));
}

// 提交数据
const handleSubmit = () => {
  roleFormRef.value.validate((isValid: boolean) => {
    if (isValid) {
      if (adminId.value) {
        postAdminInfo(formData).then((res: any) => {
          ElMessage.success(res.msg);
          dialog.visible = false;
          resetForm();
          resetQuery();
        })
      } else {
        postAdminAdd(formData).then((res: any) => {
          ElMessage.success(res.msg);
          dialog.visible = false;
          resetForm();
          resetQuery();
        })
      }
    }
  })
}

/** 关闭表单弹窗 */
function closeDialog() {
  dialog.visible = false;
  resetForm();
}

/** 重置表单 */
function resetForm() {
  roleFormRef.value.resetFields();
  roleFormRef.value.clearValidate();

  formData.id = undefined;
  formData.account = '';
  formData.nickname = '';
  formData.login_pwd = '';
  formData.login_pwd_confirmation = '';
  formData.is_root = '';
  formData.role_ids = [];
}

// 修改密码参数
const newPwd = reactive<any>({
  visible: false,
  login_pwd: '',
  login_pwd_confirmation: '',
  id: ''
});

// 修改密码
const hanldeLoginPwd = (id: number) => {
  newPwd.id = id;
  newPwd.visible = true;
}

// 提交修改密码数据
const handlePwdSubmit = () => {
  updateLoginPwd(newPwd).then((res: any) => {
    ElMessage.success(res.msg);
    newPwd.visible = false;
  })
}

const handlePwdcloseDialog = () => {
  newPwd.visible = false;
}

onMounted(() => {
  handleQuery(); // 初始化用户列表数据
});
</script>

<template>
  <div class="app-container">
    <el-row :gutter="20">

      <el-col :lg="24" :xs="24">

        <el-card shadow="never">
          <template #header>
            <div class="flex justify-between">
              <div>
                <el-button @click="openDialog()" type="primary"><i-ep-plus />新增</el-button>
              </div>
            </div>
          </template>
          <el-table v-loading="loading" :data="userList">
            <el-table-column label="管理员id" align="center" prop="id" width="100" />
            <el-table-column label="管理员账号" align="center" prop="account" />
            <el-table-column label="昵称" align="center" prop="nickname" />
            <el-table-column label="管理员" align="center" prop="status">
              <template #default="scope">
                <el-tag type="success" v-if="scope.row.is_root == 1">超级管理员</el-tag>
                <el-tag type="danger" v-else>普通管理员</el-tag>
              </template>
            </el-table-column>
            <el-table-column fixed="right" align="center" label="操作" width="220">
              <template #default="scope">
                <el-button type="primary" link size="small" @click.stop="openDialog(scope.row)">修改</el-button>
                <el-button type="primary" link size="small" @click.stop="hanldeLoginPwd(scope.row.id)">修改密码</el-button>
                <el-button type="primary" link size="small" @click.stop="handleDelete(scope.row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination v-if="total > 0" v-model:total="total" v-model:page="queryParams.page"
            v-model:limit="queryParams.ps" @pagination="handleQuery" />
        </el-card>
      </el-col>
    </el-row>

    <!-- 角色表单弹窗 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="500px" @close="closeDialog">
      <el-form ref="roleFormRef" :model="formData" :rules="rules" label-width="120px">
        <el-form-item label="登录账号" prop="account">
          <el-input :disabled="adminId == '' ? false : true" v-model="formData.account" placeholder="请输入登录账号" />
        </el-form-item>
        <el-form-item label="账号昵称" prop="nickname">
          <el-input v-model="formData.nickname" placeholder="请输入账号昵称" />
        </el-form-item>
        <template v-if="adminId == ''">
          <el-form-item label="登录密码" prop="login_pwd">
            <el-input v-model="formData.login_pwd" placeholder="请输入登录密码" />
          </el-form-item>
          <el-form-item label="确认登录密码" prop="login_pwd_confirmation">
            <el-input v-model="formData.login_pwd_confirmation" placeholder="请输入确认登录密码" />
          </el-form-item>
        </template>
        <el-form-item label="身份" prop="is_root">
          <el-radio-group v-model="formData.is_root">
            <el-radio :value="1">超级管理员</el-radio>
            <el-radio :value="2">管理员</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="formData.is_root == 2" label="角色" prop="role_ids">
          <el-select v-model="formData.role_ids" placeholder="请选择角色" clearable multiple>
            <el-option v-for="(item, index) in roleList" :key="index" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 修改密码 -->
    <el-dialog v-model="newPwd.visible" title="修改登录密码" width="500px" @close="handlePwdcloseDialog">
      <el-form :model="newPwd" label-width="120px">
        <el-form-item label="新登录密码" prop="login_pwd">
          <el-input v-model="newPwd.login_pwd" placeholder="请输入登录密码" />
        </el-form-item>
        <el-form-item label="确认新登录密码" prop="login_pwd_confirmation">
          <el-input v-model="newPwd.login_pwd_confirmation" placeholder="请输入确认登录密码" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handlePwdSubmit">确 定</el-button>
          <el-button @click="handlePwdcloseDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>